package com.mamingchao.concurrent.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by mamingchao on 2020/7/14.
 */
public class ReadWriteLockTest {

    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();
    static int value = 0;


    static void writeValue(String threadName, int newValue) {
        writeLock.lock();
        value  += newValue;
        sleepASencond();
        System.out.printf("线程 %s 写了new value, 新值为 %s", threadName, newValue);
        System.out.println();
        writeLock.unlock();
    }

    static void readValue(String threadName) {
        readLock.lock();
        sleepASencond();
        System.out.printf("线程 %s 读取了value, value 值为 %d", threadName, value);
        System.out.println();
        readLock.unlock();
    }


    private static void sleepASencond() {
        try{
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {

        for(int i=0;i< 10;i++) {
            final String threadName = "RT-" + i;
            new Thread(() -> {
               readValue(threadName);
            }).start();
        }

        for(int i=0;i< 2;i++) {
            final String threadName = "WT-" + i;
            int index = i;
            new Thread(() -> {
                writeValue(threadName,index);
            }).start();
        }

        for(int i=10;i< 20;i++) {
            final String threadName = "RT-" + i;
            new Thread(() -> {
                readValue(threadName);
            }).start();
        }

        for(int i=2;i< 4;i++) {
            final String threadName = "WT-" + i;
            int index = i;
            new Thread(() -> {
                writeValue(threadName,index);
            }).start();
        }
    }
}
